<template>
  <el-container class="GoodsDetails">
    <el-header class="mt20 flex"><span class="title fs18">商品详情</span></el-header>
    <el-main v-loading="loading">
      <el-row :gutter="20">
        <el-col v-if="form.homeImageIds" :span="12" :lg="12" :md="12" :sm="24" :xs="24" class="flexColCenter">
          <splide ref="primary" :options="primaryOptions" class="primary-splide">
            <splide-slide v-for="slide in form.homeImageIds" :key="slide.url">
              <Cimage :src="slide.url" :preview-src-list="[slide.url]" alt="slide.alt" width="100%" height="100%" fit="cover" style="cursor: pointer;" />
            </splide-slide>
          </splide>
          <splide ref="secondary" :options="secondaryOptions" class="secondary-splide">
            <splide-slide v-for="slide in form.homeImageIds" :key="slide.url">
              <Cimage :src="slide.url" alt="slide.alt" width="100%" height="100%" fit="cover" style="cursor: pointer;" />
            </splide-slide>
          </splide>
        </el-col>
        <el-col :span="12" :lg="12" :md="12" :sm="24" :xs="24" class="GoodsDetails-content">
          <h3 style="color: #606266;">{{ form.name | isNullData }}</h3>
          <p v-if="form.hot" style="color: #F56C6C;">【 {{ form.hot }} 】</p>
          <p>秒杀价：<span class="fs20" style="color: #F56C6C;">￥{{ form.price }} </span><span class="fs12" style="text-decoration: line-through;"> 【￥{{ form.oldPrice }}】</span></p>
          <p>总库存剩余：<span style="color: #606266;">{{ form.stock_num }}</span></p>
          <el-divider />
          <p>商品类别：<CcategoryCascader :category-id.sync="form.parentIdList" disabled /></p>
          <p v-for="item in form.skuList" :key="item.id">
            <span class="mr15">选择{{ item.k | isNullData }}</span>
            <el-radio-group v-if="item.v.length > 0" v-model="item.vId" size="medium" class="GoodsDetails-content-group" @change="(value) => { selectSkuChange(value, item) }">
              <el-radio-button v-for="it in item.v" :key="it.id" :label="it.id">
                <Cimage v-if="it.previewImgUrl" :src="it.previewImgUrl[0].url" width="36px" height="36px" fit="cover" class="mr10" />
                <span>{{ it.name | isNullData }}</span>
              </el-radio-button>
            </el-radio-group>
          </p>
          <p v-if="selectSkuIndex !== -1">
            <span class="mr15">已选择：</span>
            <span v-for="item in form.list[selectSkuIndex].data" :key="item.id">
              {{ item.k | isNullData }} - {{ item.name | isNullData }}，
            </span>
            <span>价格 - <span style="color:#F56C6C;">￥{{ form.list[selectSkuIndex].price }}</span>，</span>
            <span>剩余库存 - {{ form.list[selectSkuIndex].stock_num }}</span>
          </p>
          <el-tag v-if="form.skuList && form.skuList.length === 0">该商品无sku列表</el-tag>
        </el-col>
      </el-row>
      <el-row class="GoodsDetails-footer mt30">
        <el-col :span="24">
          <el-tabs type="border-card" class="GoodsDetails-footer-tabs">
            <el-tab-pane label="商品详情">
              <div class="flexCenter">
                <Cimage v-for="item in form.detailsImageIds" :key="item.id" :src="item.url" :preview-src-list="[item.url]" lazy fit="cover" width="100%" height="100%" style="cursor: pointer;" />
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </el-main>
  </el-container>
</template>
<script>
import { Splide, SplideSlide } from '@splidejs/vue-splide'
import '@splidejs/splide/dist/css/themes/splide-default.min.css'
import CcategoryCascader from '@/components/CcategoryCascader'
import {
  myGoodsDetail
} from '@/api/myGoods'
export default {
  name: 'GoodsDetails',
  components: {
    Splide,
    SplideSlide,
    CcategoryCascader
  },
  data() {
    return {
      radio1: '',
      id: '',
      loading: true,
      form: '', // 商品数据
      primaryOptions: {
        type: 'loop', // 滑块的类型
        perPage: 1, // 确定要在页面中显示的幻灯片数
        perMove: 1, // 确定一次移动的幻灯片数量
        gap: '1rem', // 幻灯片之间的间隙。CSS 格式是可以接受的
        pagination: true, // 确定是否创建分页（指示器点）
        width: '100%', // 定义滑块最大宽度，接受10em、80vw等CSS格式
        heightRatio: 0.6, // 通过与滑块宽度的比率确定幻灯片的高度
        autoplay: true, // 确定是否启用自动播放
        interval: 3000 // 毫秒为单位的自动播放间隔持续时间。
      },
      secondaryOptions: {
        type: 'slide', // 滑块的类型
        rewind: true, // 确定是否倒带滑块
        gap: '1rem', // 幻灯片之间的间隙。CSS 格式是可以接受的
        pagination: false, // 确定是否创建分页（指示器点）
        fixedWidth: 110, // 固定幻灯片的宽度，接受 CSS 格式
        fixedHeight: 70, // 修复幻灯片的高度，接受除 % 之外的 CSS 格式
        cover: true, // 将图像转换为父元素src的 css background-imageURL
        focus: 0, // 如果页面中有多张幻灯片，则确定哪张幻灯片应处于活动状态
        isNavigation: true, // 如果true，滑块使幻灯片可点击以导航另一个滑块
        updateOnMove: true, // is-active在移动滑块之前更新幻灯片的状态
        width: '100%', // 定义滑块最大宽度，接受10em、80vw等CSS格式
        heightRatio: 0.3
      },
      selectSku: {}, // 已选择的sku规格值
      selectSkuIndex: -1 // 已选择的sku规格列表的索引
    }
  },
  created() {
    if (this.$route.query.id) {
      this.id = this.$route.query.id
      this.getDetails()
    } else {
      this.$message.error('页面链接地址错误')
    }
  },
  methods: {
    // 选择sku回调
    selectSkuChange(value, item) {
      this.selectSku[item.k_s] = value // 直接用对象方式（可以替换也可以增加）
      if (Object.keys(this.selectSku).length === this.form.skuList.length) { // 通过长度判断选择完成
        this.form.list.forEach((value, index) => {
          let data = []
          for (const prop in this.selectSku) { // 符合条件的push true
            if (value[prop] === this.selectSku[prop]) {
              data.push(true)
            }
          }
          if (data.length === Object.keys(this.selectSku).length && data.every(item => item)) { // 判断数组true的长度打到要求长度才匹配正确
            this.selectSkuIndex = index // 赋值
          }
        })
      }
    },
    // 初始化
    async getDetails() {
      const res = await myGoodsDetail({ goodsId: this.id })
      if (res.code === 0) {
        const { data } = res
        if (data.parentId && data.fatherId) { // 判断返回了一二级分类id组成数组
          data['parentIdList'] = [data.fatherId.toString(), data.parentId.toString()] // 转成字符串，饿了么组件bug
        }
        if (data.list && data.list.length > 0) { // 格式化规格列表（匹配值）
          data.list.forEach(item => {
            item['data'] = []
            data.skuList.forEach(value => {
              item['data'] = this.formatSku(item, value)
            })
          })
        }
        this.loading = false
        this.form = data
        // 轮播图
        this.$nextTick(() => {
          // Set the sync target.
          this.$refs.primary.sync(this.$refs.secondary.splide)
        })
      }
    },
    formatSku(item, skuItem) { // 格式化规格列表（匹配值）
      for (const prop in item) {
        for (const key in skuItem) {
          // eslint-disable-next-line eqeqeq
          if (prop == skuItem[key]) {
            const index = skuItem.v.findIndex(it => it.id === item[prop]) // 获取索引
            item['data'].push({
              k: skuItem.k,
              key: prop,
              id: item[prop],
              name: skuItem.v[index].name
            })
          }
        }
      }
      return item['data']
    }
  }
}
</script>
<style lang="scss" scoped>
@import "~@/styles/element-variables.scss";
.GoodsDetails{
  min-width: 100%;
  height: 100vh;
  ::v-deep .el-header{
    padding: 20px 10px;
  }
  ::v-deep .el-main{
    padding: 20px 10px;
  }
  p{
    color: #909399;
  }
  &-content{
    &-group{
      ::v-deep .el-radio-button__inner{
        display: flex;
        align-items: center;
        padding: 0 14px;
        height: 36px;
        margin-bottom: 5px;
      }
    }
  }
  &-footer{
    &-tabs{
      max-width: 100%;
      width: 1440px;
      margin: 0 auto;
    }
  }
}

.primary-splide{
  width: 600px;
  ::v-deep .splide__arrows{ // 箭头
    svg{
      fill: $--color-primary;
    }
  }
}
.secondary-splide{
  width: 600px;
  margin-top: 20px;
  ::v-deep .splide__arrows{ // 箭头
    svg{
      fill: $--color-primary;
    }
  }
  .splide__slide { // 模糊
    opacity: 0.75;
  }
  .splide__slide.is-active {
    opacity: 1;
    border-color: $--color-primary !important;
  }
}
</style>

